﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Jamhee.Noctiluca.LightWiki.Markup
{
    class Image : WikiMarkup
    {
        // Sample: {img:url=http://www.google.com|title=test url being opened in a new window|size=1,2}
        private const string IMAGE = @"\{img:(url=([^\|]+))(\|title=([^\|]+))?(\|size=(\d+%?,\d+%?))?\}";

        protected override string ConvertMarkup(string text, string docFolder, Uri url, MarkupStack stack, Regex regex)
        {
            string html = text;
            MatchCollection matches = regex.Matches(html);

            foreach (Match match in matches)
            {
                if (match.Groups.Count == 7)
                {
                    string imageUrl = match.Groups[2].Value;
                    string imageTitle = match.Groups[4].Value;
                    string imageSize = match.Groups[6].Value;

                    string alter = "";
                    if (imageTitle.Length > 0)
                    {
                        alter = " alt=\"" + imageTitle + "\" title=\"" + imageTitle + "\"";
                    }

                    string size = "";
                    if (imageSize.Length > 0)
                    {
                        string[] sizes = imageSize.Split(',');
                        size = " width=\"" + sizes[0] + "\" height=\"" + sizes[1] + "\"";
                    }

                    string replacement = "<img src=\"" + CovertURL(imageUrl, url, true) + "\"" + alter + size + ">";

                    html = regex.Replace(html, replacement);
                }
            }

            return html;
        }

        protected override string MarkupRegEx
        {
            get { return IMAGE; }
        }

        public override bool AddParagraphMarkup
        {
            get { return true; }
        }
    }
}
